<template>
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item>咨询预约管理</el-breadcrumb-item>
	</el-breadcrumb>

	<el-form :inline="true" :model="queryParams" class="demo-form-inline">
		<el-form-item label="预约用户">
			<el-input v-model="queryParams.user.username" placeholder="请输入用户名" clearable @clear="queryDataList" />
		</el-form-item>
		<el-form-item label="预约咨询师">
			<el-input v-model="queryParams.counselor.counselorName" placeholder="请输入咨询师" clearable @clear="queryDataList" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="queryDataList">搜索</el-button>
			<el-button type="danger" @click="batchRemove">批量删除</el-button>
		</el-form-item>
	</el-form>

	<el-table :data="dataList" border row-key="id" style="width: 100%" @selection-change="handleSelectionChange">
		<el-table-column type="selection" fixed="left" width="40" />
		<el-table-column property="id" label="ID" fixed="left" width="60" />
		<el-table-column label="预约时间" width="180">
			<template #default="scope">
				{{ formatDate(scope.row.subscribeConsultTime) }}
			</template>
		</el-table-column>
		<el-table-column property="situationDescription" label="情况说明" width="200" />
		<el-table-column property="user.username" label="预约用户" />
		<el-table-column property="user.nickname" label="用户昵称" />
		<el-table-column property="counselor.counselorName" label="咨询师" />
		<el-table-column fixed="right" label="操作" min-width="50">
			<template #default="scope">
				<el-button type="success" size="small" @click="viewRecord(scope.row)">查看</el-button>
				<el-button type="danger" size="small" @click="deleteRecord(scope.row.id)">删除</el-button>
			</template>
		</el-table-column>
	</el-table>

	<el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
		:page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="total"
		@size-change="handleSizeChange" @current-change="handleCurrentChange" />

	<!-- 查看详情对话框 -->
	<el-dialog :title="dialogTitle" v-model="viewDialogVisible" width="700px">
		<el-form :model="viewFormData" label-width="120px">
			<el-form-item label="预约ID">
				<el-input v-model="viewFormData.id" readonly />
			</el-form-item>
			<el-form-item label="预约时间">
				<el-input :value="formatDate(viewFormData.subscribeConsultTime)" readonly />
			</el-form-item>
			<el-form-item label="情况说明">
				<el-input v-model="viewFormData.situationDescription" type="textarea" rows="4" readonly />
			</el-form-item>
			<el-form-item label="预约用户">
				<el-input v-model="viewFormData.user.username" readonly />
			</el-form-item>
			<el-form-item label="用户昵称">
				<el-input v-model="viewFormData.user.nickname" readonly />
			</el-form-item>
			<el-form-item label="咨询师">
				<el-input v-model="viewFormData.counselor.counselorName" readonly />
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="viewDialogVisible = false">关闭</el-button>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
	import { ElMessage, ElMessageBox } from 'element-plus';
	import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
	import qs from 'qs'; // 引入qs处理参数序列化

	// 类型定义
	interface User {
		id: number;
		username: string;
		nickname: string;
	}

	interface Counselor {
		id: number;
		counselorName: string;
	}

	interface SubscribeConsult {
		id: number;
		subscribeConsultTime: string;
		situationDescription: string;
		userId: number;
		counselorId: number;
		user?: User;
		counselor?: Counselor;
		del?: number;
	}

	// 全局属性
	const { appContext } = getCurrentInstance()!;
	const axios = appContext.config.globalProperties.axios;

	// 查询参数
	const queryParams = reactive({
		user: {
			username: '' // 用户名查询条件
		},
		counselor: {
			counselorName: '' // 咨询师查询条件
		},
		pageNum: 1,
		pageSize: 5
	});

	// 数据列表
	const dataList = ref<SubscribeConsult[]>([]);
	const total = ref(0);
	
	const userList = ref<User[]>([]);
	const counselorList = ref<Counselor[]>([]);

	// 查看对话框状态
	const viewDialogVisible = ref(false);
	const dialogTitle = ref('');

	// 查看表单数据
	const viewFormData = ref<SubscribeConsult>({} as SubscribeConsult);

	// 批量选择
	const multipleSelection = ref<number[]>([]);

	// 日期格式化工具函数
	const formatDate = (dateStr: string | undefined) => {
		if (!dateStr) return '';
		const date = new Date(dateStr);
		return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
	};

	// 查询数据列表
	const queryDataList = () => {
		const params = {
			...queryParams,
			user: queryParams.user,
			counselor: queryParams.counselor
		};

		axios.get('/subscribeConsult/page', {
			params: params,
			paramsSerializer: (params) => qs.stringify(params, { allowDots: true }) // 处理嵌套参数
		})
			.then((resp) => {
				if (resp.code === 200) {
					dataList.value = resp.data.list;
					total.value = resp.data.total;
				} else {
					ElMessage.error('查询失败: ' + resp.msg);
				}
			})
			.catch((err) => {
				ElMessage.error('网络错误: ' + err.message);
			});
	};

	// 加载用户列表
	const loadUserList = () => {
		axios.get('/user')
			.then((resp) => {
				if (resp.code === 200) {
					userList.value = resp.data;
				} else {
					ElMessage.error('加载用户列表失败: ' + resp.msg);
				}
			});
	};

	// 加载咨询师列表
	const loadCounselorList = () => {
		axios.get('/counselor')
			.then((resp) => {
				if (resp.code === 200) {
					counselorList.value = resp.data;
				} else {
					ElMessage.error('加载咨询师列表失败: ' + resp.msg);
				}
			});
	};

	// 生命周期钩子
	onMounted(() => {
		queryDataList();
		loadUserList();
		loadCounselorList();
	});

	// 表格选择变化
	const handleSelectionChange = (selection: SubscribeConsult[]) => {
		multipleSelection.value = selection.map((item) => item.id);
	};

	// 分页事件处理
	const handleSizeChange = (size: number) => {
		queryParams.pageSize = size;
		queryDataList();
	};

	const handleCurrentChange = (page: number) => {
		queryParams.pageNum = page;
		queryDataList();
	};

	// 查看记录
	const viewRecord = (row: SubscribeConsult) => {
		dialogTitle.value = '查看预约详情';
		viewFormData.value = { ...row };
		viewDialogVisible.value = true;
	};

	// 删除记录
	const deleteRecord = (id: number) => {
		ElMessageBox.confirm('确定要删除该预约记录吗？', '确认删除', {
			type: 'warning'
		}).then(() => {
			axios.delete(`/subscribeConsult/${id}`)
				.then((resp) => {
					if (resp.code === 200) {
						ElMessage.success('删除成功');
						queryDataList();
					} else {
						ElMessage.error(resp.msg || '删除失败');
					}
				})
				.catch((err) => {
					ElMessage.error('网络错误: ' + err.message);
				});
		});
	};

	// 批量删除
	const batchRemove = () => {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请先选择要删除的记录');
			return;
		}

		ElMessageBox.confirm(`确定要删除选中的 ${multipleSelection.value.length} 条记录吗？`, '批量删除', {
			type: 'warning'
		}).then(() => {
			axios.delete('/subscribeConsult', {
				params: { ids: multipleSelection.value.join(',') }
			})
				.then((resp) => {
					if (resp.code === 200) {
						ElMessage.success('批量删除成功');
						queryDataList();
					} else {
						ElMessage.error(resp.msg || '批量删除失败');
					}
				})
				.catch((err) => {
					ElMessage.error('网络错误: ' + err.message);
				});
		});
	};
</script>

<style scoped>
	.el-breadcrumb {
		border-bottom: 1px solid #EEEEEE;
		padding: 15px 0;
		margin-bottom: 20px;
	}

	.demo-form-inline {
		padding: 5px 0;
		margin-bottom: 20px;
	}

	.demo-form-inline .el-input,
	.demo-form-inline .el-select {
		width: 175px;
		margin-right: 5px;
	}

	.el-table {
		margin-bottom: 20px;
	}

	.el-pagination {
		text-align: right;
		margin-top: 15px;
	}

	.dialog-footer {
		text-align: right;
	}

	.el-textarea {
		width: 100%;
	}
</style>